using FairyGUI;
using UnityEngine;
using System.Collections.Generic;

public class MainUI : SingletonMono<MainUI>
{

    GButton arrangeBtn;
    GList list;
    GList skillChooseList;
    GList itemList;
    GList shortcutList; //快捷栏列表
    GButton weaponButton;
    GLoader weaponLoader;

    GComponent _mainView; 
    PopUpWindow _popWindow; 
    ArrangeWindow _arrangeWindow;  

    DataManager dataManger;

    GButton[] selectSkillBtns;
    GComponent playerStatus;
    GComponent itemPanel;
    GComponent equipPanel;

    GComponent skillPanel;
    GComponent usingSkillPanel;
    GComponent skillChoosePanel;
    GButton skillCloseButton;
    Controller skillDetailShowController;
    GComponent costPanel;
    GProgressBar mpbar; //蓝条
    GSlider hpbar; //血条
    GProgressBar mpExtraBar; //额外蓝条
    GButton ringBtn;
    GMovieClip ringAnim;
    int currentSelectSkillId = 0;
    int dragItemId = 0;

    bool isSkillPanelShowing= false;
    Transition skillShowTrans;
    

    SkillDetailWindow skillWindow;
    PlayerWindow playerWindow;
    Transition statusButtonTrans;
    Transition ringBlinkTrans;
    GButton detailButton;
    GButton statusButton;

    void Start()
    {
        //UIConfig.modalLayerColor = new Color(0f, 0f, 0f, 0.4f);
        dataManger = DataManager.GetInstance();
        dataManger.readGameInfo();
         dataManger.addItem();
         _mainView = this.GetComponent<UIPanel>().ui;
        
         _arrangeWindow = new ArrangeWindow();
         _popWindow = new PopUpWindow(() => { Debug.Log("confirm"); }, () => { Debug.Log("cancel"); });
        skillWindow = new SkillDetailWindow();

        arrangeBtn = _mainView.GetChild("arrangeBtn").asButton;
        ringBtn = _mainView.GetChild("ringBtn").asButton;
        ringAnim = ringBtn.GetChild("n2").asMovieClip;
        _mainView.GetChild("arrangeBtn").onClick.Add(() => {
            _arrangeWindow.Show();
            _arrangeWindow.modal = true;
            playerStatus.visible = false;
            itemPanel.visible = false;
            ringBtn.visible = false;
            arrangeBtn.visible = false;
            
        });
        selectSkillBtns = new GButton[4];
        UIPackage.AddPackage("Sprites");
        

        equipPanel = _mainView.GetChild("equipPanel").asCom;
        itemPanel = _mainView.GetChild("itemPanel").asCom;

        //技能相关
        usingSkillPanel = _mainView.GetChild("usingSkillPanel").asCom;
        skillCloseButton = usingSkillPanel.GetChild("n13").asButton;
        skillShowTrans = usingSkillPanel.GetTransition("slideShow");
        for (int i = 0; i < 4; i++)
        {
            selectSkillBtns[i] = usingSkillPanel.GetChild("skillBtn" + (i+1)).asButton;
        }
        usingSkillPanel.GetChild("skillOpenButton").onClick.Add(() =>
        {
            skillCloseButton.visible = true;
            skillShowTrans.Play(()=> { skillCloseButton.visible = true; });
            
        });
        skillCloseButton.onClick.Add(() =>
        {
            skillCloseButton.visible = false;
            skillShowTrans.PlayReverse();
        });
        skillChoosePanel = usingSkillPanel.GetChild("skillChoosePanel").asCom;
        
        if (skillPanel != null){
            list = skillPanel.GetChild("skillDown").asList;
        }
        if(skillChoosePanel != null)
        {
            skillChooseList = skillChoosePanel.GetChild("list").asList;
        }
        refreshSeletedSkillList();

        refreshNotSeletedSkillList();

        ringBlinkTrans = ringBtn.GetTransition("t0");
        //右侧储物戒指相关
        ringBtn.onRollOver.Add(()=>{
            Debug.Log(44);
            ((MovieClip)ringAnim.displayObject).Rewind();
            ringAnim.playing = true;
            //ringBlinkTrans.Play();
            equipPanel.visible = true;
        });
        ringBtn.onRollOut.Add(() => {
            //ringAnim.playing = false;
            //ringAnim.playing = false;
            //ringBlinkTrans.Stop();
            hideEquipPanel();
        });
        _mainView.GetChild("triggerPanel").onRollOver.Add(() => {
            equipPanel.visible = true;
        });
        _mainView.GetChild("triggerPanel").onRollOut.Add(() => {
            hideEquipPanel();
        });
      
        itemPanel.onRollOver.Add(() => {
            equipPanel.visible = true;
        });
        itemPanel.onRollOut.Add(() => {
            hideEquipPanel();
        });
        itemList = equipPanel.GetChild("itemList").asList;
        shortcutList = itemPanel.GetChild("shortcutList").asList;
        weaponButton = itemPanel.GetChild("weaponButton").asButton;

        weaponLoader = weaponButton.GetChild("spriteLoader").asLoader;
        addWeaopnEvent();
        shortcutList.itemRenderer = RenderShortCutListItem;
       
        refreshEquipList();
        refreshShortCutList();
        
        //左上角玩家状态相关
        playerWindow = new PlayerWindow();
        playerStatus = _mainView.GetChild("playerStatus").asCom;
        statusButton = playerStatus.GetChild("statusButton").asButton;
        statusButtonTrans = statusButton.asButton.GetTransition("t0");
        statusButton.onRollOver.Add(() =>
        {
            detailButton.visible = true;
            statusButtonTrans.Play();
        });
        statusButton.onRollOut.Add(() =>
        {
            detailButton.visible = false;
            statusButtonTrans.PlayReverse();
        });
        playerStatus.GetChild("statusButton").onClick.Add(showPlayerPanel);
        detailButton = playerStatus.GetChild("detailButton").asButton;
        detailButton.onRollOver.Add(() =>
        {
            statusButtonTrans.Play();
        });
        detailButton.onRollOut.Add(() =>
        {
            statusButtonTrans.PlayReverse();
        });
        detailButton.onClick.Add(showPlayerDetailPanel);
         mpbar = playerStatus.GetChild("mpBarTotal").asCom.GetChild("mpbar").asProgress;
        hpbar = playerStatus.GetChild("hpbar").asSlider;
        mpExtraBar = playerStatus.GetChild("mpBarTotal").asCom.GetChild("mpextraBar").asProgress;
        mpbar.value = 70;
        hpbar.value = 70;
        mpExtraBar.value = 25;
        
    }

   
    void showPlayerDetailPanel() {
        playerWindow.Show();
        equipPanel.visible = true; 
    }

    public void hideEquipPanel()
    {
        if (!playerWindow.isShowing)
        {
            equipPanel.visible = false;
        }
        
    }

    public void hideArrangePanel()
    {
        
        playerStatus.visible = true;
        itemPanel.visible = true;
        ringBtn.visible = true;
        arrangeBtn.visible = true;
    }

    void addWeaopnEvent()
    {
        weaponButton.onDrop.Add((EventContext context) =>
        {
            int id = (int)context.data;
            InventoryItem item1 = DataManager.GetInstance().inventoryInfos.Find(x => x.id == id);
            if (item1.type == "weapon")
            {
                //button.icon = (string)context.data;
                dataManger.equipItem(0, id);
                
                int item = dataManger.itemIds.Find(x => x == id);
                dataManger.itemIds.Remove(item);
                refreshEquipList();
                refreshShortCutList();
            }
            else
            {
                Debug.Log("���Ƿ���");
            }

        });

    }

    //刷新已选技能列表
    void refreshSeletedSkillList()
    {
        for(int index = 0; index < 4; index++)
        {
            GButton button = selectSkillBtns[index];
            button.title = "" + index;
            GLoader spriteLoader = button.GetChild("skillIcon").asLoader;
            button.data = "";

            if (index < dataManger.selectedSkillIds.Count)
            {
                int id = dataManger.selectedSkillIds[index];
                button.data = id+"_"+index;
                SkillItem skill = dataManger.skillInfos.Find(x => x.id == id);
                if (skill != null)
                {
                    spriteLoader.url = "ui://CommonPackage/" + skill.icon;
                }
            }
            else
            {
                button.data = 0 + "_" + index;
                spriteLoader.url = "";
            }
            button.onClick.Add(showSkillChoosePanel);
        }
        
        /*list.itemRenderer = RenderSkillListItem;
        list.numItems = 6;*/
    }

   
    public void refreshEquipList()
    {
        itemList.itemRenderer = RenderEquipListItem;
        itemList.numItems = 5;
    }

    
    void refreshNotSeletedSkillList()
    {
        
        //list.SetVirtualAndLoop();
        skillChooseList.itemRenderer = RenderNotSelectSkillListItem;

        skillChooseList.numItems = 3;
    }

    public void refreshShortCutList()
    {
        shortcutList.numItems = 6;
        weaponLoader.url = "";
        EquipPos pos = dataManger.equipPoses.Find(x => x.gridIndex == 0);
        if (pos != null)
        {
            InventoryItem item = DataManager.GetInstance().inventoryInfos.Find(x => x.id == pos.id);
            if (item != null)
            {
                weaponLoader.url = "ui://CommonPackage/"+item.icon;
            }

        }
    }

    //�����б�ˢ��
    void RenderSkillListItem(int index, GObject obj)
    {
        GButton button = obj.asButton;
        button.title = "" + index;
        GLoader spriteLoader = button.GetChild("skillIcon").asLoader;
        button.data = 0;
       

        if(index< dataManger.selectedSkillIds.Count)
        {
            int id = dataManger.selectedSkillIds[index];
            button.data = id;
            SkillItem skill = dataManger.skillInfos.Find(x => x.id == id);
            if(skill != null)
            {
                spriteLoader.url = "ui://CommonPackage/"+skill.icon;
            }
        }
        else
        {
            spriteLoader.url = "";
        }
        button.onClick.Add(showSkillChoosePanel);

    }

    void RenderNotSelectSkillListItem(int index, GObject obj)
    {
        showItemIcon(obj.asCom.GetChild("skillBtn1").asButton,index*2);
        showItemIcon(obj.asCom.GetChild("skillBtn2").asButton,index*2+1);
    }

    void showItemIcon(GButton button,int index)
    {
        //GButton button = obj.asButton;
        button.title = "" + index;

        GLoader spriteLoader1 = button.GetChild("skillIcon").asLoader;
        List<int> notSelectIds = new List<int>();
        foreach (var item in dataManger.skillInfos)
        {
            if (!dataManger.selectedSkillIds.Contains(item.id))
            {
                notSelectIds.Add(item.id);
            }
        }
        spriteLoader1.url = "";
        if (index < notSelectIds.Count)
        {
            int id = notSelectIds[index];
            button.data = id;
            SkillItem skill = dataManger.skillInfos.Find(x => x.id == id);
            if (skill != null)
            {
                spriteLoader1.url = "ui://CommonPackage/" + skill.icon;
            }
        }

        button.onClick.Add(chooseSkill);
    }

    void RenderEquipListItem(int index, GObject obj)
    {
        GButton button = obj.asButton;
        button.title = "" + index;
        
        //Debug.Log(button.title);
        GLoader spriteLoader2 = button.GetChild("spriteLoader").asLoader;
        spriteLoader2.data = 0;
        dataManger = DataManager.GetInstance();
        spriteLoader2.url = "";
        
        if (index < dataManger.itemIds.Count)
        {
            int id = dataManger.itemIds[index];
            InventoryItem item = dataManger.inventoryInfos.Find(x => x.id == id);
            if (item != null)
            {
                spriteLoader2.url = "ui://CommonPackage/" + item.icon;
                button.data = id;
                spriteLoader2.url = "ui://CommonPackage/" + item.icon;
                button.draggable = true;
                button.onDragStart.Add(addDragItem);
            }
        }
        button.onRollOver.Add(showEquipDetail);
        button.onRollOut.Add(()=>{
            skillWindow.Hide();
        });
    }

    void showEquipDetail(EventContext context)
    {
        //int index = (int)((context.sender as GObject).data);

        //GObject obj = GRoot.inst.touchTarget;
        
        GObject obj = context.sender as GObject;
        
        //skillWindow.= obj.parent;
        Vector2 screenPos = obj.LocalToGlobal(Vector2.zero);
        Debug.Log(screenPos);
        skillWindow.SetXY(screenPos.x + obj.width, screenPos.y);
        //skillWindow.x = v2.x;// + obj.width - 50;
       // skillWindow.y = v2.y;// - obj.height / 2;

        skillWindow.Show();
    }

    void addDragItem(EventContext context)
    {
        context.PreventDefault();
        
        GObject obj = context.sender as GObject;
        GLoader spriteLoader = obj.asCom.GetChild("spriteLoader").asLoader;
        spriteLoader.data = (int)obj.data;
        DragManager.inst.StartDrag(spriteLoader, spriteLoader.url, spriteLoader.data);
    }


    //渲染右下角装备栏
    void RenderShortCutListItem(int index, GObject obj)
    {
        GButton button = obj.asButton;
        button.title = "" + index;
        GLoader spriteLoader2 = button.GetChild("spriteLoader").asLoader;
        spriteLoader2.data = 0;

        spriteLoader2.url = "";

        button.onDrop.Add((EventContext context) =>
        {
            int id = (int)context.data;
            InventoryItem item1 = DataManager.GetInstance().inventoryInfos.Find(x => x.id == id);
            if(item1.type == "armor")
            {
                dataManger.equipItem(index+1, id);
                refreshEquipList();
                refreshShortCutList();
            } else
            {
                Debug.Log("不是防具");
            }
            
        });
        if (index <= 2)
        {
            EquipPos pos = dataManger.equipPoses.Find(x => x.gridIndex == index+1);
            
            if (pos !=null  && pos.id != 0)
            {
                InventoryItem item1 = dataManger.inventoryInfos.Find(x => x.id == pos.id);
                spriteLoader2.url = "ui://CommonPackage/" + item1.icon;
            }

        }
        button.GetChild("numText").text = (index + 1).ToString();
      
    }


    //显示技能选择面板
    void showSkillChoosePanel(EventContext context)
    {

        string[] arr = ((string)(context.sender as GObject).data).Split('_');
        skillShowTrans.Play();
        //isSkillPanelShowing = true;
        currentSelectSkillId =  System.Convert.ToInt32(arr[0]);
        int currentSlotIndex = System.Convert.ToInt32(arr[1]);
        /*for(int i = 0; i < 4; i++)
        {
            selectSkillBtns[i].GetChild("highlight").visible = false;
        }*/
        //selectSkillBtns[currentSlotIndex].GetChild("highlight").visible = true;
    }

    //选择技能
    void chooseSkill(EventContext context)
    {
        int chooseSkillId = (int)(context.sender as GObject).data;
        //如果当前选了空技能，直接add
        if (currentSelectSkillId == 0)
        {
            Debug.Log("新增");
            dataManger.selectedSkillIds.Add(chooseSkillId);
        }
        //��ǰѡ�м��ܣ��Ƴ��ɼ���ID�������¼���
        else {
            Debug.Log("移除并新增");
            int index = dataManger.selectedSkillIds.IndexOf(currentSelectSkillId);
            dataManger.selectedSkillIds[index] = chooseSkillId;

        }
        skillShowTrans.PlayReverse();
        refreshSeletedSkillList();
        refreshNotSeletedSkillList();
    }

    public void StartDrag(EventContext context)
    {
        dragItemId = (int)(context.sender as GObject).data;
        Debug.Log(dragItemId);
    }

    public void showPlayerPanel()
    {
        Window p = new PlayerWindow();
        p.Show();
    }



}